#Alexander F. Gazmararian
#afg2@princeton.edu
#January 9, 2024

#Purpose: Process migration data for robustness check

#Load packages
library(tidycensus)
library(tidyverse)
library(here)

#Load matched data 
g <- readRDS(here("data", "output", "matched_df.rds"))

g$fips5 <- str_pad(g$fips, 5, "left", "0")
g$fips_state <- substr(g$fips5, 0, 2)
g$fips_cty <- substr(g$fips5, 3, 6)

g.fips <- subset(g, select = c(fips_state, fips_cty))
g.fips <- unique(g.fips)

n_distinct(g.fips$fips_state)

#Download census data

# list of states
state.list <- unique(g.fips$fips_state)

acs.2010 <- list()
for (j in 1:length(state.list)) {
  state.sub <- subset(g.fips, fips_state == state.list[[j]])
  # Get data
  acs.2010[[j]] <- get_flows(
    geography = "county",
    variables = c("POP1YR", "POP1YRAGO"),
    breakdown = c("AGE", "SEX", "RACE"),
    breakdown_labels = TRUE,
    year = 2010,
    output = "wide",
    state = state.sub$fips_state[[1]],
    county = state.sub$fips_cty
  )
  acs.2010[[j]]$year <- 2010
}

acs.2015 <- list()
for (j in 1:length(state.list)) {
  state.sub <- subset(g.fips, fips_state == state.list[[j]])
  # Get data
  acs.2015[[j]] <- get_flows(
    geography = "county",
    variables = c("POP1YR", "POP1YRAGO"),
    breakdown = c("AGE", "SEX", "RACE"),
    breakdown_labels = TRUE,
    year = 2015,
    output = "wide",
    state = state.sub$fips_state[[1]],
    county = state.sub$fips_cty
  )
  acs.2015[[j]]$year <- 2015
}

acs.2010.out <- do.call(rbind, acs.2010)
acs.2015.out <- do.call(rbind, acs.2015)

acs.out <- rbind(acs.2010.out, acs.2015.out)
saveRDS(acs.out, here("data", "inter", "acs_raw.rds"))
